package com.shuma.upms.logging.service;

import com.shuma.upms.logging.domain.dto.OperationLogMessage;
import com.shuma.upms.logging.domain.entity.OperationLog;
import com.shuma.upms.logging.mapper.OperationLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class LogPersistenceService {

    @Autowired
    private OperationLogMapper operationLogMapper;


     //将从MQ接收到的消息持久化到数据库
    @Transactional
    public void saveLog(OperationLogMessage event) {
        if (event == null) {
            log.warn("接收到空的日志事件，跳过处理。");
            return;
        }

        OperationLog operationLog = new OperationLog();

        operationLog.setUserId(event.getUserId());
        operationLog.setAction(event.getAction());
        operationLog.setIp(event.getIp());
        operationLog.setDetail(event.getDetail()); // 记录操作详情

        try {
            operationLogMapper.insert(operationLog);
            log.info("成功保存日志，ID 为 {}。操作行为为 {}，用户 ID 为 {}",
                    operationLog.getLogId(), operationLog.getAction(), operationLog.getUserId());
        } catch (Exception e) {
            log.error("无法将日志保存到数据库。事件：{}", event, e);
            throw new RuntimeException("日志事件的数据库插入失败。", e);
        }
    }
}